package com.zhoug.widget.popup;

import android.content.Context;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;


import com.zhoug.common.adapters.recycler.BaseRecyclerViewAdapter;
import com.zhoug.common.adapters.recycler.BaseViewHolder;
import com.zhoug.common.utils.AppUtils;
import com.zhoug.common.utils.LogUtils;
import com.zhoug.widget.R;

import java.util.List;

import androidx.annotation.DrawableRes;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

/**
 * 列表popupWindow 图片:文字
 */
public abstract class ListPopupManager2<T> {
    private static final String TAG = ">>>ListPopupManager2";
    private Context context;
    private BasePopupWindow popupWindow;
    private RecyclerView recyclerView;
    private Adapter adapter;
    private View anchor;//锚点
    private List<T> data;
    private OnSelectListener onSelectListener;//选择监听
    private PopupWindow.OnDismissListener dismissListener;

    private int selection = 0;//当前选择
    private int textColorSelected = Color.parseColor("#38B966");
    private int textColor = Color.parseColor("#333333");

    private @DrawableRes
    int itemBackground;

    private int itemPaddingTop = 10;
    private int itemPaddingBottom = 10;
    private int itemPaddingLeft = 10;
    private int itemPaddingRight = 10;


    public ListPopupManager2(Context context) {
        this.context = context;
        init();

    }

    private void init() {
        popupWindow = new BasePopupWindow(context);
        View view = LayoutInflater.from(context).inflate(R.layout.widgets_layout_popup_list2, null);
        recyclerView = view.findViewById(R.id.recyclerView);
        recyclerView.setLayoutManager(new LinearLayoutManager(context));
//        recyclerView.addItemDecoration(new MDividerItemDecoration(context, OrientationHelper.VERTICAL));
        adapter = new Adapter();
        recyclerView.setAdapter(adapter);
        popupWindow.setContentView(view);
        popupWindow.setOutsideTouchable(true);
        popupWindow.setFocusable(true);
        //不能设置为null否则点击外部不能关闭,设置透明背景
        popupWindow.setTransparentBackground();
        popupWindow.setAnimationStyle(R.style.widgets_anim_window_popu_anchor_down);

        if (dismissListener != null) {
            popupWindow.setOnDismissListener(dismissListener);
        }


    }

    /**
     * 如果窗口宽高为0则测量宽高
     */
    private void measureWindowSize() {
        if (popupWindow.getWidth() <= 0 || popupWindow.getHeight() <= 0) {
            View contentView = popupWindow.getContentView();
            AppUtils.measureView(contentView);
            if (popupWindow.getWidth() <= 0) {
                popupWindow.setWidth(contentView.getMeasuredWidth());
            }
            if (popupWindow.getHeight() <= 0) {
                popupWindow.setHeight(contentView.getMeasuredHeight());
            }
        }
    }

    public void show() {
        //showAsDropDown 的对齐方式是v控件的左下角与popupWindow的控件左上角对齐
        //而popupWindow不会超出屏幕，所以显示效果是紧贴右边框。
        //小幅设置偏移量真实位置还是超出边框，窗口依旧会紧贴右边框，并不会看出有什么效果
        LogUtils.d(TAG, "show: ");
        measureWindowSize();
        popupWindow.showAsDropDown(anchor);

       /* Disposable subscribe = Observable.timer(1, TimeUnit.SECONDS)
                .compose(SchedulersProvider.apply())
                .subscribe(i -> {
                    LogUtils.d(TAG, "show: i="+i);
                    int width = popupWindow.getWidth();
                    int height = popupWindow.getHeight();
                    LogUtils.d(TAG, "show: width="+width+",height="+height);



                }, throwable -> {
                    LogUtils.d(TAG, "show: "+throwable.getMessage());
                });*/
    }

    public void showAtLocation(int gravity, int x, int y) {
        //第一个参数是View类型的parent,虽然这里参数名是parent，其实，不是把PopupWindow放到这个parent里，
        // 并不要求这个parent是一个ViewGroup，这个参数名让人误解。官方文档
        // “a parent view to get the android.view.View.getWindowToken() token from
        //”,这个parent的作用应该是调用其getWindowToken()方法获取窗口的Token,所以，
        // 只要是该窗口(父类窗口)上的控件（例如：按钮控件）就可以了
        measureWindowSize();
        popupWindow.showAtLocation(anchor, gravity, x, y);
    }


    private class Adapter extends BaseRecyclerViewAdapter<T> implements View.OnClickListener {


        @Override
        public int getLayoutId(int viewType) {
            return R.layout.widgets_layout_popup_list_item2;
        }


        @NonNull
        @Override
        public BaseViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            BaseViewHolder vh = super.onCreateViewHolder(parent, viewType);
            vh.itemView.setPadding(itemPaddingLeft, itemPaddingTop, itemPaddingRight, itemPaddingBottom);

            return vh;
        }

        @Override
        public void onBindData(BaseViewHolder holder, T data, int position, int viewType) {
            if (data != null) {
                ImageView ivIcon = holder.getView(R.id.iv_icon);
                TextView tvText = holder.getView(R.id.tv_text);
                LogUtils.d(TAG, "onBindData:selection=" + selection + ", data=" + data);

                tvText.setText(getShowText(data));
                //选中
                if (selection == position) {
                    tvText.setTextColor(textColorSelected);
                    ivIcon.setVisibility(View.VISIBLE);
                } else {
                    tvText.setTextColor(textColor);
                    ivIcon.setVisibility(View.INVISIBLE);
                }

                if (itemBackground != 0) {
                    holder.itemView.setBackgroundResource(itemBackground);
                }

                holder.itemView.setTag(position);
                holder.itemView.setOnClickListener(this);

//                LogUtils.d(TAG, "onBindData: data="+data);
            }

        }


        @Override
        public void onClick(View v) {
            int position = (int) v.getTag();
            selection = position;
            notifyDataSetChanged();
            if (onSelectListener != null) {
                popupWindow.dismiss();
                onSelectListener.onSelected(position);
            }

        }
    }

    public abstract String getShowText(T data);

    public List<T> getData() {
        return data;
    }

    public void setData(List<T> data) {
        this.data = data;
        adapter.setData(data);
        adapter.notifyDataSetChanged();
    }

    public View getAnchor() {
        return anchor;
    }

    public void setAnchor(View anchor) {
        this.anchor = anchor;
    }

    public OnSelectListener getOnSelectListener() {
        return onSelectListener;
    }

    public void setOnSelectListener(OnSelectListener onSelectListener) {
        this.onSelectListener = onSelectListener;
    }

    public int getTextColorSelected() {
        return textColorSelected;
    }

    public void setTextColorSelected(int textColorSelected) {
        this.textColorSelected = textColorSelected;
    }

    public int getTextColor() {
        return textColor;
    }

    public void setTextColor(int textColor) {
        this.textColor = textColor;
    }

    public int getSelection() {
        return selection;
    }

    public void setSelection(int selection) {
        if (this.selection != selection) {
            this.selection = selection;
            if (adapter != null) {
                adapter.notifyDataSetChanged();
            }
        }

    }


    public void setItemBackground(@DrawableRes int itemBackground) {
        this.itemBackground = itemBackground;
    }

    public void setItemPadding(int itemPaddingLeft, int itemPaddingTop, int itemPaddingRight, int itemPaddingBottom) {
        this.itemPaddingLeft = itemPaddingLeft;
        this.itemPaddingTop = itemPaddingTop;
        this.itemPaddingRight = itemPaddingRight;
        this.itemPaddingBottom = itemPaddingBottom;
    }

    public PopupWindow getPopupWindow() {
        return popupWindow;
    }

    public interface OnSelectListener {
        void onSelected(int position);
    }


    public void setOnDismissListener(PopupWindow.OnDismissListener dismissListener) {
        this.dismissListener = dismissListener;
        if (popupWindow != null) {
            popupWindow.setOnDismissListener(dismissListener);
        }
    }
}
